<template>
  <div>
    <el-form :inline="true" :model="searchForm" width="30%">
      <el-form-item label="数据库名称"><el-input v-model="searchForm.dbName" placeholder="请输入数据库名称"/></el-form-item>
      <el-form-item label="数据库备注"><el-input v-model="searchForm.remark" placeholder="请输入数据库备注" /></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="success" @click="refreshDbManagements">刷新</el-button>
    <el-button type="success" @click="showDialog('addOrEditVisible')">新增</el-button>
    <el-button type="success" @click="deleteDatas">批量删除</el-button>
    <el-button type="success" @click="testConnection">连接测试</el-button>
    <el-button type="success" @click="showAddTableDialog">新增表</el-button>
    <el-tooltip content="从本系统数据库同步到指定目标" placement="top">
      <el-button type="success" @click="syncForward">正向同步</el-button>
    </el-tooltip>
    <el-tooltip content="从所选连接同步到本系统" placement="top">
      <el-button type="success" @click="syncBackward">反向同步</el-button>
    </el-tooltip>

    <el-table :data="dbManagement" style="width: 100%"
              @selection-change="selection => {selectedDbManagements = selection;}">
      <el-table-column type="selection" width="30"/>
      <el-table-column prop="id" label="ID" width="100" v-if="false"/>
      <el-table-column prop="dbType" label="数据库类型" width="100"/>
      <el-table-column prop="dbName" label="数据库名称"/>
      <el-table-column prop="userName" label="用户名"/>
      <el-table-column prop="dbIp" label="IP地址"/>
      <el-table-column prop="dbPort" label="端口号"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button type="success"
                     @click="handleTableMaintain(scope.row)">表维护
          </el-button>
          <el-button type="success"
                     @click="showDialog('addOrEditVisible',najlForm,scope.row)">编辑
          </el-button>
          <el-button type="success" @click="deleteData(scope.row.id, scope.row.dbName)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-config-provider :locale="zhCn">
      <el-pagination style="display: flex; justify-content: flex-end; margin-top: 10px;"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pagination.currentPage"
                     :page-sizes="[10, 20, 50, 100, 200, 1000,2000]"
                     :page-size="pagination.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="pagination.total"/>
    </el-config-provider>
    <el-dialog title="数据库信息编辑" v-model="addOrEditVisible" width="30%"
               :close-on-click-modal="false" @close="closeDialog('addOrEditVisible')"><!-- 弹出窗 -->
      <el-form ref="najlFormRef" :model="najlForm" :rules="rules">
        <el-form-item label="数据库类型" prop="dbType" label-width="100px">
          <el-select v-model="najlForm.dbType" placeholder="请选择类型">
            <el-option label="MySql" value="MySql"></el-option>
            <el-option label="Oracle" value="Oracle"></el-option>
            <el-option label="SqlServer" value="SqlServer"></el-option>
            <el-option label="Db2" value="Db2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbName" label-width="100px">
          <el-input v-model="najlForm.dbName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="连接IP" prop="dbIp" label-width="100px">
          <el-input v-model="najlForm.dbIp" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="端口号" prop="dbPort" label-width="100px">
          <el-input v-model="najlForm.dbPort" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName" label-width="100px">
          <el-input v-model="najlForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPswd" label-width="100px">
          <el-input type="password" v-model="najlForm.userPswd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="100px">
          <el-input v-model="najlForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog('addOrEditVisible')">取 消</el-button>
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="新增表" v-model="addTableVisible" width="70%" :close-on-click-modal="false"
               class="full-width-dialog">
      <el-form :model="tableForm" width="100%">
        <el-form-item label=" " label-width="30">
          <div class="field-list-container">
            <!-- Table name and comment row -->
            <div class="header-row">
              <el-form-item label="表名" label-width="50">
                <el-input v-model="tableForm.tableName" placeholder="请输入表名" class="styled-input"/>
              </el-form-item>
              <el-form-item label="注释" label-width="50">
                <el-input v-model="tableForm.tableComment" placeholder="请输入注释" class="styled-input"/>
              </el-form-item>
            </div>
            <div class="field-list-section">
              <span class="field-list-label"><b>字段列表</b></span>
            </div>

            <!-- Fields table -->
            <el-table :data="tableForm.dbColumnReqList" style="width: 100%; margin-top: 16px;">
              <el-table-column type="index" label="序号" width="100"/>
              <el-table-column prop="columnName" label="字段名">
                <template #default="scope">
                  <el-input v-model="scope.row.columnName"/>
                </template>
              </el-table-column>
              <el-table-column prop="columnType" label="字段类型">
                <template #default="scope">
                  <el-input v-model="scope.row.columnType"/>
                </template>
              </el-table-column>
              <el-table-column prop="columnLength" label="长度">
                <template #default="scope">
                  <el-input v-model="scope.row.columnLength"/>
                </template>
              </el-table-column>
              <el-table-column prop="columnComment" label="注释">
                <template #default="scope">
                  <el-input v-model="scope.row.columnComment"/>
                </template>
              </el-table-column>
              <el-table-column prop="isRequired" label="必填" width="80">
                <template #default="scope">
                  <el-checkbox v-model="scope.row.isRequired"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button type="success" @click="copyField(scope.$index)">复制</el-button>
                  <el-button type="danger" @click="removeField(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
    <span class="dialog-footer">
      <el-button type="success" @click="addField">新增字段</el-button>
      <el-button type="success" @click="addTableVisible = false">取 消</el-button>
      <el-button type="success" @click="addTable">确 定</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {ElMessageBox} from 'element-plus';
import {reactive, ref, onMounted, nextTick} from 'vue';
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import tableMaintain from './TableMaintain.vue';

export default {
  name: 'DbManagementList',
  setup() {
    const dbManagement = ref([]);
    const searchForm = reactive({dbName: '', remark: ''});
    const addOrEditVisible = ref(false);
    const najlForm = reactive({
      id: 0,
      dbName: '',
      dbType: 'MySql',
      dbIp: '127.0.0.1',
      dbPort: '3306',
      userName: 'root',
      userPswd: '',
      remark: ''
    });
    const tableForm = reactive({
      dbId: 0,
      tableName: '',
      tableComment: '',
      dbColumnReqList: [
        {
          columnName: 'id',
          columnType: 'bigint',
          columnLength: 64,
          columnComment: '主键',
          required: true,
          editing: false
        },
        {
          columnName: 'create_user_id',
          columnType: 'varchar',
          columnLength: 64,
          columnComment: '创建用户ID',
          required: true,
          editing: false
        },
        {
          columnName: 'create_time',
          columnType: 'date',
          columnLength: 64,
          columnComment: '创建时间',
          required: true,
          editing: false
        },
        {
          columnName: 'update_time',
          columnType: 'date',
          columnLength: 64,
          columnComment: '更新时间',
          required: true,
          editing: false
        },
        {
          columnName: 'remark',
          columnType: 'text',
          columnLength: -1,
          columnComment: '备注',
          required: false,
          editing: false
        }
      ]
    });
    const selectedDbManagements = ref([]);
    const rules = reactive({
      dbName: [{required: true, message: '请输入数据库名称', trigger: 'blur'},
        {min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur'},
        {pattern: /^[a-zA-Z_1-9]+$/, message: '数据库名称只能包含英文字母、数字和下划线', trigger: 'blur'}],
      dbType: [{required: true, message: '请选择数据库类型', trigger: 'change'}],
      dbIp: [{required: true, message: '请输入连接IP', trigger: 'blur'}],
      dbPort: [{required: true, message: '请输入端口号', trigger: 'blur'}],
      userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
      userPswd: [{required: true, message: '请输入密码', trigger: 'blur'}]
    });
    const najlFormRef = ref(null);
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });

    const fetchDbManagements = async (params = {}) => {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/dbManagement/listPage`, {
          ...params,
          pageNum: pagination.currentPage,
          pageSize: pagination.pageSize
        });
        if (response.data.success) {
          dbManagement.value = response.data.data.list;
          pagination.total = response.data.data.total;
        } else {
          console.error('Request failed:', response.data.message);
        }
      } catch (error) {
        console.error('Failed to fetch dbManagement:', error);
      }
    };
    const onSearch = () => {
      fetchDbManagements({
        dbName: searchForm.dbName,
        remark: searchForm.remark,
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize
      });
    };

    const handleSizeChange = (newSize) => {
      pagination.pageSize = newSize;
      fetchDbManagements();
    };

    const handleCurrentChange = (newPage) => {
      pagination.currentPage = newPage;
      fetchDbManagements();
    };

    const showDialog = (visibleName, formObj, srcData) => {
      const visibilityMap = {addOrEditVisible};
      visibilityMap[visibleName].value = true;
      nextTick(() => {
        if (srcData != undefined) Object.assign(formObj, srcData);
      });
    };
    const closeDialog = (visibleName) => {
      const visibilityMap = {addOrEditVisible};
      visibilityMap[visibleName].value = false;
      najlFormRef.value.resetFields();
      najlForm.id = 0;
    };
    const validForm = async (najlFormRef) => {
      const valid = await new Promise((resolve) => {
        najlFormRef.value.validate((valid) => {
          resolve(valid);
        });
      });
      if (!valid) {
        ElMessageBox.alert('数据验证失败，请检查输入内容是否正确！！！');
        return false;
      }
      return valid;
    };
    const dalinConfirm = async (name, callback) => {
      ElMessageBox.confirm(
          `您确定要删除 "${name}" 吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        callback();
      }).catch(() => {
        // 用户取消删除
      });
    };

    const reqDeal = async (url, reqType, reqParams, callback) => {
      url = `${process.env.VUE_APP_API_BASE_URL}` + url;
      try {
        let response;
        if (reqType === 'post') {
          response = await axios.post(url, reqParams);
        } else if (reqType === 'get') {
          response = await axios.get(url, {params: reqParams});
        } else if (reqType === 'delete') {
          response = await axios.delete(url);
        } else {
          throw new Error('Unsupported request type');
        }
        callback(response);
      } catch (error) {
        console.error('Request failed:', error);
      }
    };

    const addOrUpdate = async () => {
      if (!await validForm(najlFormRef)) return;
      await reqDeal('/dbManagement/addOrUpdate', 'post', najlForm, () => {
        addOrEditVisible.value = false;
        refreshDbManagements();
      });
    };
    const deleteData = async (id, name) => {
      dalinConfirm(name, () => {
        reqDeal(`/dbManagement/delete/${id}`, 'delete', najlForm, () => {
          dbManagement.value = dbManagement.value.filter(dbManagement => dbManagement.id !== id);
          refreshDbManagements();
        });
      });
    };
    const deleteDatas = async () => {
      if (selectedDbManagements.value.length === 0) {
        ElMessageBox({message: '请选择要删除的记录', type: 'warning'});
        return;
      }
      // 构建提示信息
      const names = selectedDbManagements.value.map(dbManagement => dbManagement.dbName).join(', ');
      dalinConfirm(names, () => {
        const ids = selectedDbManagements.value.map(dbManagement => dbManagement.id);
        reqDeal(`/dbManagement/deleteByIds`, 'post', ids, () => {
          dbManagement.value = dbManagement.value.filter(dbManagement => !ids.includes(dbManagement.id));
          refreshDbManagements();
        });
      });
    };

    const testConnection = async () => {
      if (selectedDbManagements.value.length === 0) {
        ElMessageBox({message: '请选择要操作的记录', type: 'warning'});
        return;
      }
      const ids = selectedDbManagements.value.map(dbManagement => dbManagement.id);
      reqDeal(`/dbManagement/connectTest/`, 'post', {"ids": ids}, (response) => {
        console.log("Response:", response.data); // 输出响应数据到控制台
        if (response.data.success) {
          ElMessageBox.alert(response.data.data, '提示', {type: 'success'});
        }
      });
    };

    const showAddTableDialog = () => {
      if (selectedDbManagements.value.length === 0 || selectedDbManagements.value.length > 1) {
        ElMessageBox({message: '请选择要操作的记录且只能选择一条记录', type: 'warning'});
        return;
      }
      addTableVisible.value = true;
    };

    const addField = () => {
      tableForm.dbColumnReqList.push({
        columnName: '',
        columnType: '',
        columnLength: '',
        columnComment: '',
        required: false,
        editing: true
      });
    };
    const copyField = (index) => {
      const newField = {...tableForm.dbColumnReqList[index], editing: true};
      tableForm.dbColumnReqList.splice(index + 1, 0, newField);
    };
    const removeField = (index) => {
      tableForm.dbColumnReqList.splice(index, 1);
    };

    const addTable = async () => {
      tableForm.dbId = selectedDbManagements.value[0].id;
      try {
        reqDeal(`/dbManagement/addTable/`, 'post', tableForm, (response) => {
          console.log("Response:", response.data); // 输出响应数据到控制台
          if (response.data.success) {
            ElMessageBox.alert(response.data.data, '提示', {type: 'success'});
          }
        });
        // addTableVisible.value = false;
      } catch (error) {
        console.error('Failed to add table:', error);
      }
    };

    const syncForward = async () => {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/dbManagement/syncDb`, selectedDbManagements.value);
        if (response.data.success) {
          ElMessageBox.alert('正向同步成功', '提示', {
            type: 'success'
          });
        } else {
          ElMessageBox.alert('正向同步失败', '提示', {
            type: 'error'
          });
        }
      } catch (error) {
        console.error('Failed to sync forward:', error);
      }
    };

    const syncBackward = async () => {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/dbManagement/backwardSyncDb`, selectedDbManagements.value);
        if (response.data.success) {
          ElMessageBox.alert('反向同步成功', '提示', {
            type: 'success'
          });
        } else {
          ElMessageBox.alert('反向同步失败', '提示', {
            type: 'error'
          });
        }
      } catch (error) {
        console.error('Failed to sync backward:', error);
      }
    };

    const refreshDbManagements = () => {
      fetchDbManagements();
    };

    const resetForm = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''; // 将所有值设置为空字符串
        // 如果字段类型不同，可以在这里添加更多的逻辑来处理不同的初始值
      });
      refreshDbManagements();
    };
    const handleTableMaintain = (slectedRow) => {
      tableMaintain.value.showEditDialog(slectedRow);
    };

    const addTableVisible = ref(false);

    onMounted(() => {
      fetchDbManagements(); // 页面加载时立即获取数据库列表
    });

    return {
      zhCn,
      tableMaintain,
      najlFormRef,
      dbManagement,
      searchForm,
      addOrEditVisible,
      najlForm,
      tableForm,
      selectedDbManagements,
      rules,
      fetchDbManagements,
      onSearch,
      showDialog,
      handleTableMaintain,
      closeDialog,
      addOrUpdate,
      deleteData,
      deleteDatas,
      testConnection,
      showAddTableDialog,
      addField,
      copyField,
      removeField,
      addTable,
      syncForward,
      syncBackward,
      refreshDbManagements,
      resetForm,
      addTableVisible,
      pagination,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>


<style scoped>
.el-select {
  width: 100%; /* 确保下拉框宽度足够 */
}

/* Make inputs take full width of their container */
.search-form :deep(.el-input) {
  width: 100%;
}

.header-row {
  display: flex;
  gap: 20px; /* 增加间距 */
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.header-row .el-form-item {
  margin-right: 0;
  width: 100%;
}

.styled-input :deep(.el-input__wrapper) {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.styled-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.styled-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 调整标签样式 */
.header-row .el-form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 移除对话框的内边距 */
.full-width-dialog :deep(.el-dialog__body) {
  padding: 10px !important;
}

/* 确保表格内容占满宽度 */
.field-list-container {
  width: 100%;
  padding: 0;
}

/* 调整表格列的宽度 */
:deep(.el-table) {
  width: 100% !important;
  margin: 0;
}

/* 调整页脚按钮区域的内边距 */
:deep(.el-dialog__footer) {
  padding: 10px 20px;
}
</style>